#!/bin/bash
cd $LFS/sources/pkg || exit 1;
source ./pkglib.sh || exit 3;
source ./utils.sh || exit 2;
WHOAMI=$(whoami);
if [[ $WHOAMI != "root" && $WHOAMI != "lfs" ]]; then
	errcho "Login as root or lfs user";
	exit 3;
fi

PKG_NAME=$(pkgname $1 $2) || exit 4;
PKG_VERSION=$(pkgversion $1 $2) || exit 5;

if [ ! -x $1/make_$PKG_NAME.sh ]; then
	errcho "make file dosn't exists or isn't executable: $1/make_$PKG_NAME";
	exit 8;
fi

# checking dependencies
if [ -e /sources/pkg/$1/$PKG_NAME/deps.pkg ]; then
    MISSING=""
    DEPS=$(cat /sources/pkg/$1/$PKG_NAME/deps.pkg | tr -s '[:blank:]' ':' | tr -s '[:space:]' '\n' | tr ':' ' ' | grep -v '^#' || echo "") || exit 9;
    IFS=$'\n';
    for p in $DEPS; do
		DEP_NAME=$(echo $p | cut -d' ' -f1);
		if [[ $DEP_NAME != "!"* ]]; then
            DEP_VERSION=$(echo $p | cut -d' ' -f2);
            INSTVER=$(pkginstver $DEP_NAME);
            if [[ $INSTVER == "" || $(versionmatch $DEP_VERSION $INSTVER 2> /dev/null) == "" ]]; then
                MISSING="$MISSING$DEP_NAME-$DEP_VERSION ";
            fi
        fi
    done;
    if [[ $MISSING != "" ]]; then
        errcho "Package dependencies not satisfied; missing:";
        errcho $(echo $MISSING);
        exit 10;
    fi
fi    

echo "Make package $1/$PKG_NAME";

[ ! -e /usr/pkg/$PKG_NAME ] || rm -Rf /usr/pkg/$PKG_NAME || {
	errcho "Can not remove package install destination";
	exit 8;
}

if [[ $WHOAMI == "root" ]]; then
	su -p -c "PATH=$PATH; $1/make_$PKG_NAME.sh" lfs || {
		errcho "Aborted make process with code $?";
		exit 6;
	}
else
	$1/make_$PKG_NAME.sh || {
		errcho "Aborted make process with code $?";
		exit 7;
	}
fi
echo " --OK--"
